package me.minetsh.imaging;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.yuyh.library.imgsel.ISNav;
import com.yuyh.library.imgsel.config.ISListConfig;

import me.minetsh.imaging.core.IMGMode;
import me.minetsh.imaging.core.IMGText;
import me.minetsh.imaging.core.file.IMGAssetFileDecoder;
import me.minetsh.imaging.core.file.IMGDecoder;
import me.minetsh.imaging.core.file.IMGFileDecoder;
import me.minetsh.imaging.core.util.IMGUtils;
import me.minetsh.imaging.gallery.model.IMGChooseMode;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 *
 */

public class IMGEditActivity extends IMGEditBaseActivity {

    private static final int MAX_WIDTH = 1024;

    private static final int MAX_HEIGHT = 1024;

    public static final String EXTRA_IMAGE_URI = "IMAGE_URI";

    public static final String EXTRA_IMAGE_SAVE_PATH = "IMAGE_SAVE_PATH";

    private static final String TAG = "IMGEditActivity";

    @Override
    public void onCreated() {
        Log.d(TAG, "onCreated 被调用了，编辑页面初始化完成");
    }

    @Override
    public Bitmap getBitmap() {
        Log.d(TAG, "getBitmap 被调用，开始加载原始图片");
        Intent intent = getIntent();
        if (intent == null) {
            Log.e(TAG, "getBitmap: Intent 为空，无法获取图片");
            return null;
        }

        Uri uri = intent.getParcelableExtra(EXTRA_IMAGE_URI);
        if (uri == null) {
            Log.e(TAG, "getBitmap: 图片 URI 为空");
            return null;
        }

        Log.d(TAG, "getBitmap: 图片 URI = " + uri.toString());

        IMGDecoder decoder = null;

        String path = uri.getPath();
        if (!TextUtils.isEmpty(path)) {
            switch (uri.getScheme()) {
                case "asset":
                    Log.d(TAG, "getBitmap: 使用资产文件解码器");
                    decoder = new IMGAssetFileDecoder(this, uri);
                    break;
                case "file":
                    Log.d(TAG, "getBitmap: 使用文件解码器");
                    decoder = new IMGFileDecoder(uri);
                    break;
                default:
                    Log.w(TAG, "getBitmap: 不支持的 URI scheme: " + uri.getScheme());
                    break;
            }
        } else {
            Log.w(TAG, "getBitmap: URI 路径为空");
        }

        if (decoder == null) {
            Log.e(TAG, "getBitmap: 未能创建解码器，返回 null");
            return null;
        }

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 1;
        options.inJustDecodeBounds = true;

        Log.d(TAG, "getBitmap: 开始读取图片尺寸信息");
        decoder.decode(options);

        Log.d(TAG, "getBitmap: 原始图片宽度 = " + options.outWidth + ", 高度 = " + options.outHeight);

        if (options.outWidth > MAX_WIDTH) {
            options.inSampleSize = IMGUtils.inSampleSize(Math.round(1f * options.outWidth / MAX_WIDTH));
            Log.d(TAG, "getBitmap: 调整采样率 inSampleSize = " + options.inSampleSize);
        }

        if (options.outHeight > MAX_HEIGHT) {
            options.inSampleSize = Math.max(options.inSampleSize,
                    IMGUtils.inSampleSize(Math.round(1f * options.outHeight / MAX_HEIGHT)));
            Log.d(TAG, "getBitmap: 调整采样率 inSampleSize = " + options.inSampleSize);
        }

        options.inJustDecodeBounds = false;

        Bitmap bitmap = decoder.decode(options);
        if (bitmap == null) {
            Log.e(TAG, "getBitmap: 图片解码失败，bitmap 为 null");
            return null;
        }

        Log.d(TAG, "getBitmap: 图片解码成功，返回 Bitmap");
        return bitmap;
    }

    @Override
    public void onText(IMGText text) {
        Log.d(TAG, "onText 被调用，添加文字贴图: " + text.toString());
        mImgView.addStickerText(text);
    }

    @Override
    public void onImg() {
        Log.d(TAG, "onImg 被调用，准备选择图片进行贴图");
        Toast.makeText(this, "图片贴图", Toast.LENGTH_SHORT).show();
        // 自由配置选项
        ISListConfig config = new ISListConfig.Builder()
                .multiSelect(false)
                .needCamera(false)
                .btnBgColor(Color.GRAY)
                .btnTextColor(Color.BLUE)
                .statusBarColor(Color.parseColor("#3F51B5"))
                .title("选择图片进行贴图")
                .titleColor(Color.WHITE)
                .titleBgColor(Color.parseColor("#3F51B5"))
                .maxNum(1)
                .build();
        Log.d(TAG, "启动图片选择器");
        ISNav.getInstance().toListActivity(this, config, 777);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d(TAG, "onActivityResult: requestCode = " + requestCode + ", resultCode = " + resultCode);
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 777) {
            if (resultCode == RESULT_OK && data != null) {
                List<String> pathList = data.getStringArrayListExtra("result");
                if (pathList == null || pathList.size() == 0) {
                    Log.w(TAG, "添加贴图失败，路径列表为空");
                    Toast.makeText(this, "添加贴图失败~", Toast.LENGTH_SHORT).show();
                    return;
                }
                Log.d(TAG, "添加贴图，路径：" + pathList.get(0));
                mImgView.addStickerIMG(pathList.get(0));
            } else {
                Log.w(TAG, "添加贴图失败，用户取消或数据为空");
                Toast.makeText(this, "添加贴图失败~", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onModeClick(IMGMode mode) {
        Log.d(TAG, "onModeClick 被调用，当前模式: " + mImgView.getMode() + ", 新模式: " + mode);
        IMGMode cm = mImgView.getMode();
        if (cm == mode) {
            mode = IMGMode.NONE;
            Log.d(TAG, "切换到 NONE 模式");
        }
        mImgView.setMode(mode);
        updateModeUI();

        if (mode == IMGMode.CLIP) {
            Log.d(TAG, "进入裁剪模式");
            setOpDisplay(OP_CLIP);
        }
    }

    @Override
    public void onUndoClick() {
        IMGMode mode = mImgView.getMode();
        Log.d(TAG, "onUndoClick 被调用，当前模式: " + mode);
        if (mode == IMGMode.DOODLE) {
            Log.d(TAG, "撤销涂鸦操作");
            mImgView.undoDoodle();
        } else if (mode == IMGMode.MOSAIC) {
            Log.d(TAG, "撤销马赛克操作");
            mImgView.undoMosaic();
        }
    }

    @Override
    public void onCancelClick() {
        Log.d(TAG, "onCancelClick 被调用，结束编辑页面，返回取消结果");
        setResult(RESULT_CANCELED);
        finish();
    }

    @Override
    public void onDoneClick() {
        Log.d(TAG, "onDoneClick 被调用，准备保存图片");
        String path = getIntent().getStringExtra(EXTRA_IMAGE_SAVE_PATH);
        Log.d(TAG, "保存路径: " + path);
        if (!TextUtils.isEmpty(path)) {
            Bitmap bitmap = mImgView.saveBitmap();
            if (bitmap != null) {
                FileOutputStream fout = null;
                try {
                    fout = new FileOutputStream(path);
                    boolean result = bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fout);
                    Log.d(TAG, "图片压缩保存结果: " + result);
                } catch (FileNotFoundException e) {
                    Log.e(TAG, "保存文件未找到异常", e);
                } finally {
                    if (fout != null) {
                        try {
                            fout.close();
                        } catch (IOException e) {
                            Log.e(TAG, "关闭文件输出流异常", e);
                        }
                    }
                }
                Log.d(TAG, "图片保存成功，设置结果为 RESULT_OK 并结束页面");
                setResult(RESULT_OK);
                finish();
                return;
            } else {
                Log.e(TAG, "保存图片失败，bitmap 为 null");
            }
        } else {
            Log.w(TAG, "保存路径为空，不能保存图片");
        }
        Log.d(TAG, "设置结果为 RESULT_CANCELED 并结束页面");
        setResult(RESULT_CANCELED);
        finish();
    }

    @Override
    public void onCancelClipClick() {
        Log.d(TAG, "onCancelClipClick 被调用，取消裁剪操作");
        mImgView.cancelClip();
        setOpDisplay(mImgView.getMode() == IMGMode.CLIP ? OP_CLIP : OP_NORMAL);
    }

    @Override
    public void onDoneClipClick() {
        Log.d(TAG, "onDoneClipClick 被调用，完成裁剪操作");
        mImgView.doClip();
        setOpDisplay(mImgView.getMode() == IMGMode.CLIP ? OP_CLIP : OP_NORMAL);
    }

    @Override
    public void onResetClipClick() {
        Log.d(TAG, "onResetClipClick 被调用，重置裁剪框");
        mImgView.resetClip();
    }

    @Override
    public void onRotateClipClick() {
        Log.d(TAG, "onRotateClipClick 被调用，旋转裁剪框");
        mImgView.doRotate();
    }

    @Override
    public void onColorChanged(int checkedColor) {
        Log.d(TAG, "onColorChanged 被调用，画笔颜色更改为: " + checkedColor);
        mImgView.setPenColor(checkedColor);
    }
}